package com.ytf.dogbox.location.google;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import java.util.Iterator;

public class LocationUtils {

    private static final long REFRESH_TIME = 5000L;
    private static final float METER_POSITION = 0.0f;
    private static ILocationListener mLocationListener;
    private static LocationListener listener = new MyLocationListener();
    private static GpsStatus.Listener satelliteListener=new SatelliteLister();
    private static int gpscount = 0;
    private static LocationManager manager;
    private static Context mContext;

    private static class MyLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {//定位改变监听
            Log.e("TAG", "onLocationChanged: 定位改变监听" + location.toString());
            if (mLocationListener != null) {
                mLocationListener.onSuccessLocation(location);
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {//定位状态监听
            Log.e("TAG", "onStatusChanged location: 定位状态监听" + provider + ";" + status);
        }

        @Override
        public void onProviderEnabled(String provider) {//定位状态可用监听
            Log.e("TAG", "onProviderEnabled location: 定位状态可用监听========" + provider);
        }

        @Override
        public void onProviderDisabled(String provider) {//定位状态不可用监听
            Log.e("TAG", "onProviderDisabled location: 定位状态不可用监听++++++++++" + provider);
        }

    }

    private static class SatelliteLister implements GpsStatus.Listener{

        @Override
        public void onGpsStatusChanged(int event) {
            gpscount = 0;
            if (event == GpsStatus.GPS_EVENT_FIRST_FIX) {
                //第一次定位
                Log.e("tiwolf", "onGpsStatusChanged: 第一次定位");
            } else if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
                //卫星状态
                Log.e("tiwolf", "onGpsStatusChanged: 卫星状态");
                if (mContext!=null){
                    //高版本的权限检查
                    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                    }
                    GpsStatus gpsStatus = manager.getGpsStatus(null);//取当前状态
                    int maxSatellites=gpsStatus.getMaxSatellites();//获取卫星颗数的默认最大值
                    //创建一个迭代器保存所有卫星
                    Iterator<GpsSatellite> it=gpsStatus.getSatellites()
                            .iterator();
                    while (it.hasNext() && gpscount<=maxSatellites){
                        GpsSatellite s=it.next();
                        //可见卫星数量
                        if (s.usedInFix()){
                            //已经定位卫星数量
                            gpscount++;
                            Log.e("tiwolf", "onGpsStatusChanged: 定位卫星信噪比"+s.getPrn() );
                            Log.e("tiwolf", "onGpsStatusChanged: 可以使用的卫星++++++++"+gpscount);
                        }
                    }
                    Log.e("tiwolf", "onGpsStatusChanged: 已经定位的卫星数量"+gpscount);

                }

            }else if (event==GpsStatus.GPS_EVENT_STARTED){
                Log.e("tiwolf", "onGpsStatusChanged: gps定位开始");
            }else if (event==GpsStatus.GPS_EVENT_STOPPED){
                Log.e("tiwolf", "onGpsStatusChanged: gps定位结束了");
            }
        }
    }

    /**
     * GPS获取定位方式
     */
    public static Location getGPSLocation(@NonNull Context context) {
        Location location = null;
        manager = getLocationManager(context);
        mContext=context;
        //高版本的权限检查
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
        if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {//是否支持GPS定位
            //获取最后的GPS定位信息，如果是第一次打开，一般会拿不到定位信息，一般可以请求监听，在有效的时间范围可以获取定位信息
            Log.e("TAG", "getGPSLocation: gps开始去定位");
            location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            Log.e("TAG", "getGPSLocation: gps结束定位");
        }
        return location;
    }

    /**
     * network获取定位方式
     */
    public static Location getNetWorkLocation(Context context) {
        Location location = null;
        manager = getLocationManager(context);
        mContext=context;
        //高版本的权限检查
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
        if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {//是否支持Network定位
            //获取最后的network定位信息
            Log.e("TAG", "getNetWorkLocation: 网络开始定位");
            location = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            Log.e("TAG", "getNetWorkLocation: 网络结束定位");
        }else {
            Log.e("TAG", "getNetWorkLocation: 不支持网络定位");
        }
        return location;
    }

    /**
     * 获取最好的定位方式
     */
    public static Location getBestLocation(Context context) {
        Location location;
        manager = getLocationManager(context);
        mContext=context;
        Criteria c = new Criteria();//Criteria类是设置定位的标准信息（系统会根据你的要求，匹配最适合你的定位供应商），一个定位的辅助信息的类
        c.setPowerRequirement(Criteria.POWER_LOW);//设置低耗电
        c.setAltitudeRequired(true);//设置需要海拔
        c.setBearingAccuracy(Criteria.ACCURACY_COARSE);//设置COARSE精度标准
        c.setAccuracy(Criteria.ACCURACY_LOW);//设置低精度
        //... Criteria 还有其他属性，就不一一介绍了
        String provider = manager.getBestProvider(c, true);
        Log.e("TAG", "getBestLocation: 最佳方式定位"+provider );
        if (TextUtils.isEmpty(provider)) {
            //如果找不到最适合的定位，使用network定位
            Log.e("TAG", "getBestLocation: 最佳方式定位--开始使用网络定位" );
            location = getNetWorkLocation(context);
            Log.e("TAG", "getBestLocation: 最佳方式定位--结束使用网络定位" );
        } else {
            //高版本的权限检查
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return null;
            }
            //获取最适合的定位方式的最后的定位权限
            Log.e("TAG", "getBestLocation: 最佳方式定位--开始最佳结果定位"+provider );
            location = manager.getLastKnownLocation(provider);
            Log.e("TAG", "getBestLocation: 最佳方式定位--结束最佳结果定位"+provider );
        }
        return location;
    }

    /**
     * 定位监听
     */
    public static void addLocationListener(Context context, String provider, ILocationListener locationListener) {
        mContext=context;
        addLocationListener(context, provider, REFRESH_TIME, METER_POSITION, locationListener);
    }

    /**
     * 定位监听
     */
    public static void addLocationListener(Context context, String provider, long time, float meter, ILocationListener locationListener) {
        Log.e("TAG", "addLocationListener: GPS定位监听=====");
        if (locationListener != null) {
            mLocationListener = locationListener;
        }
        if (listener == null) {
            listener = new MyLocationListener();
        }
        manager = getLocationManager(context);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        manager.addGpsStatusListener(satelliteListener);
        manager.requestLocationUpdates(provider, time, meter, listener);
    }

    /**
     * 取消定位监听
     */
    public static void unRegisterListener(Context context) {
//        Log.e("TAG", "unRegisterListener location: 取消监听");
        if (listener != null) {
//            Log.e("TAG", "unRegisterListener location: 取消监听1111111111111111");
            manager = getLocationManager(context);
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
//            Log.e("TAG", "unRegisterListener location: 取消监听222222222222222222222");
            //移除定位监听
            manager.removeUpdates(listener);
            manager=null;
            listener=null;
            satelliteListener=null;
            mContext=null;
//            System.gc();        //回收下资源
//            Log.e("TAG", "unRegisterListener location: 取消监听33333333333333333333333333333333");
        }
    }

    private static LocationManager getLocationManager(@NonNull Context context) {
        return (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    }

    /**
     * 自定义接口
     */
    public interface ILocationListener {
        void onSuccessLocation(Location location);
    }
}
